package com.xky.example_student.interceptor;

import com.xky.example_student.annotation.RequirePermission;
import com.xky.example_student.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(PermissionInterceptor.class);
    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是方法处理器，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequirePermission permission = handlerMethod.getMethodAnnotation(RequirePermission.class);

        // 如果没有权限注解，直接通过
        if (permission == null) {
            return true;
        }

        // 获取权限key列表并检查权限
        String[] permissionKeys = permission.value();
        Map<String, Boolean> permissions = permissionService.getAllPermissions();

        // 调试日志：输出当前权限map和请求的keys
        log.info("[权限拦截] 当前权限map: {}", permissions);
        log.info("[权限拦截] 请求的权限: {}", String.join(", ", permissionKeys));
        log.info("[权限拦截] 权限逻辑: {}", permission.logic());
        
        // 根据逻辑类型进行权限检查
        boolean hasPermission = false;
        
        if (permission.logic() == RequirePermission.PermissionLogic.OR) {
            // OR逻辑：任意一个权限满足即可
            for (String permissionKey : permissionKeys) {
                if (permissions.containsKey(permissionKey) && permissions.get(permissionKey)) {
                    log.info("[权限拦截] OR逻辑权限检查通过: {}", permissionKey);
                    hasPermission = true;
                    break;
                }
            }
        } else {
            // AND逻辑：所有权限都必须满足（默认）
            hasPermission = true;
            for (String permissionKey : permissionKeys) {
                if (!permissions.containsKey(permissionKey) || !permissions.get(permissionKey)) {
                    log.warn("[权限拦截] AND逻辑权限检查失败: {}", permissionKey);
                    hasPermission = false;
                    break;
                }
            }
        }
        
        if (!hasPermission) {
            log.warn("[权限拦截] 权限检查失败");
            handleNoPermission(response, permission.message());
            return false;
        }
        
        log.info("[权限拦截] 权限检查通过");
        

        return true;
    }

    private void handleNoPermission(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        PrintWriter out = response.getWriter();
        out.write("{\"code\":0,\"msg\":\"" + message + "\"}");
        out.flush();
        out.close();
    }
}
